package com.wyp168.juc.sync;

/**
 * @ClassName ThreadDemo001
 * @Description TODO
 * @Author wyp168
 * @Date 2022/9/4 11:14
 */
class Share {
    //初始值 number
    private int number = 0;
    //+1 方法
    public synchronized void add() {
        //如果number值不为0，线程进入等待状态
        if (number != 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //执行 +1操作
        number ++;
        System.out.println(Thread.currentThread().getName() + "-->" + number);
        //通知其他线程
        this.notifyAll();
    }

    // -1的方法
    public synchronized void sub() {
        //如果number值不为0，线程进入等待状态
        if (number != 1) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //执行 +1操作
        number --;
        System.out.println(Thread.currentThread().getName() + "-->" + number);

        //通知其他线程
        this.notifyAll();
    }
}
public class ThreadDemo001 {
    public static void main(String[] args) {
        Share share = new Share();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                share.add();
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                share.sub();
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                share.add();
            }
        }, "CC").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                share.sub();
            }
        }, "DD").start();
    }
}
